﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartParkingServer.IService;
using SmartParkingServer.Models;
using System.IO;
using System;
using System.Net.Http.Headers;

namespace SmartParkingServer.Controllers
{
    //    api/file/list
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        //读取数据库中的文件列表
        IFileService _fileService;
        public FileController(IFileService fileService)
        {
                _fileService = fileService;
        }

        [HttpGet]
        [Route("list")]// 需要加鉴权？不需要。因为这个逻辑是在登录操作之前
        public IActionResult GetFileList()
        {
            var result = _fileService.Query<UpgradeFileModel>(f => f.FileId > 0 && f.state == 1);// EFCore
            // 从数据库获取相关的文件信息   文件名-文件MD5
            return new JsonResult(result);
        }

        /// <summary>
        /// 下载文件方法，      http://localhost:5000/api/file/download/Halcon算子手册(中文复印版).pdf
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        [HttpGet("download/{filename}")] //路由
        public IActionResult Download([FromRoute] string filename)
        {
            //var filePath = Path.Combine(Path.Combine(_configuration.Read("FileFolder"), "upgrade"), filename); //文件所在路径
            //'D:\Zhaoxi.EDU\Jovan\01-VIP\[2021]WPF上位机工业互联\20220128WPF上位机Course049SmartParking(6)\src\Zhaoxi.SmartParking.Server\Zhaoxi.SmartParking.Server\\bin
            //\net5.0-windowsWebFiles\UpgradeFiles\Halcon算子手册(中文复印版).pdf'.”


            //D:\Zhaoxi.EDU\Jovan\Vip_src\Zhaoxi.SmartParking.Server\Zhaoxi.SmartParking.Server\bin\Debug\net5.0\WebFiles\UpgradeFiles
            var root = System.Environment.CurrentDirectory;
            root = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string filePath = Path.Combine(root, @"WebFiles\UpgradeFiles", filename);
            ResFileStream fs = new ResFileStream(filePath, FileMode.Open, FileAccess.Read);

            var type = new MediaTypeHeaderValue("application/oct-stream").MediaType;

            //enableRangeProcessing 是否启动断点续传
            return File(fs, contentType: type, filename, enableRangeProcessing: true);
        }
    }

    internal class ResFileStream : FileStream
    {
        public ResFileStream(string path, FileMode mode, FileAccess access) : base(path, mode, access) { }

        /// <param name="array"></param>
        /// <param name="offset">偏移量</param>
        /// <param name="count">读取的最大字节数</param>
        /// <returns></returns>
        public override int Read(byte[] array, int offset, int count)
        {
            // 此处可以限制下载速度
            //count = 256;
            //Thread.Sleep(10);
            return base.Read(array, offset, count);
        }
    }
}
